import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getAreaCodeData, type AreaItem } from '@/api/areaCode'

export const useAreaStore = defineStore('area', () => {
  // 状态
  const provinces = ref<AreaItem[]>([])
  const cities = ref<AreaItem[]>([])
  const districts = ref<AreaItem[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 选中的地区
  const selectedProvince = ref<string>('')
  const selectedCity = ref<string>('')
  const selectedDistrict = ref<string>('')

  // 计算属性
  const isDataLoaded = computed(() => provinces.value.length > 0)
  
  const selectedProvinceInfo = computed(() => 
    provinces.value.find(p => p.id === selectedProvince.value)
  )
  
  const selectedCityInfo = computed(() => 
    cities.value.find(c => c.id === selectedCity.value)
  )
  
  const selectedDistrictInfo = computed(() => 
    districts.value.find(d => d.id === selectedDistrict.value)
  )

  // 操作
  async function loadAreaData() {
    if (isDataLoaded.value) return // 已加载则不重复加载
    
    loading.value = true
    error.value = null
    
    try {
      const response = await getAreaCodeData()
      console.log('API响应数据:', response)
      
      if (response.code && response.code !== 200) {
        throw new Error(response.message || '服务器返回错误')
      }
      
      if (!response.data || !Array.isArray(response.data)) {
        throw new Error('返回的数据格式不正确')
      }
      
      if (response.data.length === 0) {
        throw new Error('返回的数据为空')
      }
      
      // 验证数据结构
      console.log('开始验证数据结构...')
      console.log('响应数据预览:', {
        dataLength: response.data.length,
        firstItem: response.data[0],
        dataType: typeof response.data[0]
      })
      
      const firstItem = response.data[0]
      if (!firstItem) {
        throw new Error('数据数组为空或第一项为空')
      }
      
      // 更灵活的字段检查
      const hasId = firstItem.id !== undefined && firstItem.id !== null
      const hasName = firstItem.name !== undefined && firstItem.name !== null
      const hasCode = firstItem.code !== undefined && firstItem.code !== null
      const hasValue = firstItem.value !== undefined && firstItem.value !== null
      const hasAreaCode = firstItem.areaCode !== undefined && firstItem.areaCode !== null
      const hasAreaName = firstItem.areaName !== undefined && firstItem.areaName !== null
      const hasLabel = firstItem.label !== undefined && firstItem.label !== null
      
      console.log('字段检查结果:', {
        hasId, hasName, hasCode, hasValue, hasAreaCode, hasAreaName, hasLabel,
        actualFields: Object.keys(firstItem)
      })
      
      // 支持多种字段名组合
      if (!hasId && !hasCode && !hasValue && !hasAreaCode) {
        throw new Error(`缺少ID字段。实际字段: ${Object.keys(firstItem).join(', ')}`)
      }
      
      if (!hasName && !hasAreaName && !hasLabel) {
        throw new Error(`缺少名称字段。实际字段: ${Object.keys(firstItem).join(', ')}`)
      }
      
      // 标准化数据格式
      const normalizedData = response.data.map(item => ({
        id: item.id || item.code || item.value || item.areaCode || '',
        name: item.name || item.label || item.areaName || '',
        pid: item.pid || item.parentId || item.parent || item.parentCode || '0',
        level: item.level || 1,
        children: item.children || item.sub || item.subAreas || []
      }))
      
      console.log('数据标准化完成，标准化后的第一项:', normalizedData[0])
      
      provinces.value = normalizedData
      console.log(`成功加载 ${normalizedData.length} 个省份数据`)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载地区数据失败'
      error.value = errorMessage
      console.error('加载地区数据失败:', err)
      
      // 如果是CORS错误，提供更友好的错误信息
      if (errorMessage.includes('CORS') || errorMessage.includes('Network')) {
        error.value = 'CORS跨域错误，请确保服务器正在运行并配置了代理'
      }
    } finally {
      loading.value = false
    }
  }

  function selectProvince(provinceId: string) {
    selectedProvince.value = provinceId
    selectedCity.value = ''
    selectedDistrict.value = ''
    
    const province = provinces.value.find(p => p.id === provinceId)
    cities.value = province?.children || []
    districts.value = []
  }

  function selectCity(cityId: string) {
    selectedCity.value = cityId
    selectedDistrict.value = ''
    
    const city = cities.value.find(c => c.id === cityId)
    districts.value = city?.children || []
  }

  function selectDistrict(districtId: string) {
    selectedDistrict.value = districtId
  }

  function resetSelection() {
    selectedProvince.value = ''
    selectedCity.value = ''
    selectedDistrict.value = ''
    cities.value = []
    districts.value = []
  }

  return {
    // 状态
    provinces,
    cities,
    districts,
    loading,
    error,
    selectedProvince,
    selectedCity,
    selectedDistrict,
    
    // 计算属性
    isDataLoaded,
    selectedProvinceInfo,
    selectedCityInfo,
    selectedDistrictInfo,
    
    // 操作
    loadAreaData,
    selectProvince,
    selectCity,
    selectDistrict,
    resetSelection
  }
})